package com.ajmd.onlineexam.controller;

import com.ajmd.onlineexam.baseUtil.CommonResult;
import com.ajmd.onlineexam.baseUtil.JWTUtils;
import com.ajmd.onlineexam.entity.AdminPO;
import com.ajmd.onlineexam.entity.AdminPO;
import com.ajmd.onlineexam.entity.StudentPO;
import com.ajmd.onlineexam.enumeration.AppExceptionCodeEnum;
import com.ajmd.onlineexam.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ajmd
 * @since 2023/5/1 12:53
 */
@Api("管理员接口")
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Resource
    private AdminService adminService;


    @ApiOperation("通过account查询管理员")
    @GetMapping("/select")
    public CommonResult findAdminByAccount(@RequestParam String account){
        AdminPO admin = adminService.findAdminById(account);
        return CommonResult.ok().data("user",admin);
    }

    @ApiOperation("管理员登录")
    @PostMapping("/login")
    public CommonResult adminLogin(@RequestParam String account,
                                     @RequestParam String password){
        //登录数据校验
        if(StringUtils.isBlank(account)){
            return CommonResult.error(AppExceptionCodeEnum.ACCOUNT_NOT_EMPTY);
        }
        if(StringUtils.isBlank(password)){
            return CommonResult.error(AppExceptionCodeEnum.PASSWORD_NOT_EMPTY);
        }
        AdminPO adminPO = adminService.findAdminById(account);
        if(ObjectUtils.isEmpty(adminPO)){
            return CommonResult.error(AppExceptionCodeEnum.ACCOUNT_NOT_EXISTS);
        }
        if(!adminPO.getPassword().equals(password)){
//        if(!adminPO.getPassword().equals(DigestUtils.md5Hex(password))){
            return CommonResult.error(AppExceptionCodeEnum.PASSWORD_ERROR);
        }
        Map<String, String> map = new HashMap<>();
        map.put("account",account);
        String token = JWTUtils.getToken(map);
        return CommonResult.ok("登录成功").data("token",token).data("user",adminPO);
    }

//    @ApiOperation("修改管理员信息")
//    @PutMapping("/update")
//    public CommonResult updateStudentByPO(@RequestBody StudentPO student){
//        int num = studentService.studentUpdate(student);
//        if(num==0){
//            return CommonResult.error(AppExceptionCodeEnum.UPDATE_ERR)
//                    .appendMessage("未更新任何信息");
//        }
//        return CommonResult.ok("信息更新成功");
//    }

}
